<template>
  <el-switch
    v-model="status"
    :active-value="1"
    :inactive-value="0"
    @change="handleChange"
  />
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updateUserStatus, updateRoleStatus, updateMenuStatus, updateAuthStatus } from '@/api'

const props = defineProps({
  row: {
    type: Object,
    required: true
  },
  prop: {
    type: String,
    required: true
  }
})

const status = ref(props.row[props.prop])

// 监听外部状态变化
watch(() => props.row[props.prop], (val) => {
  status.value = val
})

// 根据组件所在页面选择对应的更新接口
const getUpdateApi = () => {
  const path = window.location.pathname
  if (path.includes('user')) return updateUserStatus
  if (path.includes('role')) return updateRoleStatus
  if (path.includes('menu')) return updateMenuStatus
  if (path.includes('auth')) return updateAuthStatus
  return null
}

const handleChange = async (val) => {
  const updateApi = getUpdateApi()
  if (!updateApi) {
    console.error('未找到对应的状态更新接口')
    status.value = !val
    return
  }

  try {
    await updateApi({
      id: props.row.id,
      status: val
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('状态更新失败:', error)
    status.value = !val // 恢复原状态
  }
}
</script> 